package com.cy.store.controller;
 

import com.cy.store.utils.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import java.util.UUID;
 
@RestController
public class imgController {
    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
 

 
    @Value("${file-save-path}")
    private String fileSavePath;
 
 
    @PostMapping("/upload")
    public JsonResult uploadFile(MultipartFile file, HttpServletRequest request) {
        //后半段目录：  2020/03/15
        String directory = simpleDateFormat.format(new Date());

 
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        System.out.println("图片上传，保存位置：" + fileSavePath + directory);
        //给文件重新设置一个名字
        //后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;
 
        //创建这个新文件
        File newFile = new File(fileSavePath + directory + newFileName);
        //复制操作
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            System.out.println("图片上传，访问URL：" + url);
            return JsonResult.builder().data(url).message("上传成功！").code("200").build();
        } catch (IOException e) {
 
            return JsonResult.builder().data(null).message("IO异常！").code("500").build();
        }
    }
}